import type {ComposeOption} from 'echarts/core';
import * as echarts from 'echarts/core';
import type {BarSeriesOption, LineSeriesOption, PieSeriesOption} from 'echarts/charts';
import {BarChart, LineChart, PieChart} from 'echarts/charts';
import type {
  DatasetComponentOption,
  GridComponentOption,
  LegendComponentOption,
  TitleComponentOption,
  TooltipComponentOption,
} from 'echarts/components';
import {
  DatasetComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  TransformComponent,
} from 'echarts/components';

import {LabelLayout, UniversalTransition} from 'echarts/features';
import {SVGRenderer} from 'echarts/renderers';
import {Ref, unref} from 'vue';
import {throttle} from '@/utils';

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | PieSeriesOption
  | TitleComponentOption
  | LegendComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | DatasetComponentOption
>;

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  PieChart,
  LabelLayout,
  UniversalTransition,
  SVGRenderer,
]);
export default function UseCharts(elRef: Ref<HTMLDivElement>) {
  let chart: echarts.ECharts | null;

  function initChart() {
    let el = unref(elRef);
    if (!el) return;
    chart = echarts.init(el, null, { renderer: 'svg' });
  }

  function setOptions(option: ECOption) {
    if (!chart) {
      initChart();
      if (!chart) {
        console.error('echart无法获取dom');
        return;
      }
    }
    chart.setOption(option);
    window.addEventListener('resize', listener);
  }

  const listener = throttle(() => {
    chart.resize();
  }, 30);

  function destroy() {
    if (!chart) return;
    chart.dispose();
    chart = null;
    window.removeEventListener('resize', listener);
  }

  return { setOptions, destroy };
}
